package com.asset.config.web;

import com.asset.util.AssetManageException;
import com.asset.util.ExceptionResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 11725
 */
@RestControllerAdvice
public class AssetExceptionHandler {

    @ExceptionHandler(AssetManageException.class)
    public ResponseEntity<ExceptionResult> handleAssetException(AssetManageException e) {
        ExceptionResult result = new ExceptionResult(e.getMessage());
        return ResponseEntity.status(e.getStatus()).body(result);
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ExceptionResult> handleOtherRuntimeException(RuntimeException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ExceptionResult(e.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ExceptionResult> handleBindException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ExceptionResult(message));
    }
}
